package com.yxzx.ebs.handler;

import com.yxzx.common.YxzxResult;
import com.yxzx.ebs.util.JwtUtils;
import com.yxzx.ebs.util.NoneAuth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Copyright (C), 2018-2020
 * FileName: LoginInterceptor
 * Author:   kongfanyu
 * Date:     2020/9/24 10:04
 */
@Slf4j
@CrossOrigin
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("执行登录拦截器.......");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //如果被@NoneAuth注解代表不需要登录验证，直接通过
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        log.info("执行登录拦截器......."+method.getName()+"\n"+method+"\n"+method.isAnnotationPresent(NoneAuth.class));
        //如果这个方法包括NoneAuth注解，说明是登录方法，不拦截
        //if(method.isAnnotationPresent(NoneAuth.class)) return true;
        //token验证
        String authStr = request.getHeader("token");
        log.info("执行登录拦截器token......."+authStr);
        //验证token通过
        if (JwtUtils.checkToken(authStr)){
            request.setAttribute("userId", JwtUtils.getMemberIdByJwtToken(request));
            return true;
        }
        //验证未通过
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOpt("result", YxzxResult.error().data("msg","Token验证失败"));
        String s = jsonObject.toString();
        log.info("执行登录拦截器验证失败返回数据......."+s);
        response.getWriter().write(jsonObject.toString());
        return false;
    }
}
